package team.kirohuji.service.impl.tidings;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import team.kirohuji.domain.article.Article;
import team.kirohuji.domain.tidings.Notify;
import team.kirohuji.domain.tidings.Subscription;
import team.kirohuji.domain.tidings.UserNotify;
import team.kirohuji.domain.user.User;
import team.kirohuji.repository.jpa.tidings.NotifyRepository;
import team.kirohuji.repository.jpa.tidings.SubscriptionRepository;
import team.kirohuji.repository.jpa.tidings.UserNotifyRepository;
import team.kirohuji.repository.jpa.user.UserRepository;
import team.kirohuji.repository.mongodb.article.ArticleRepository;
import team.kirohuji.service.message.ProducerService;
import team.kirohuji.service.tidings.NotifyService;

@Service("notifyService")
public class NotifyServiceImpl implements NotifyService {
	@Autowired
	public UserRepository userRepository;
	
	@Autowired
	public NotifyRepository notifyRepository;
	
	@Autowired
	public UserNotifyRepository userNotifyRepository;

	@Autowired  
	@Qualifier("articleRepository")  
	public ArticleRepository articleRepository;
	
	@Autowired
	public SubscriptionRepository subscriptionRepository;
/*	
	@Autowired
	public SubscriptionConfigRepository subscriptionConfigRepository;*/
	
	@Resource
	public ProducerService producerService;

	@Override
	public Notify createAnnounce(String topic,String content, Integer senderId) {
		producerService.sendTopicMessage(topic,content);
		User user=userRepository.getOne(senderId);
		return notifyRepository.save(new Notify(content, 4, 1, "系统公告", "强制关注", senderId,user.getUserName()));
	}

	
	@Override
	public Notify createRemind(Integer targetId, String targetType, String action, String content, Integer senderId) {
		//给所有订阅此主题的所有在线人发布消息
		String topic="Online.User."+senderId+".subscribe";
		String message=senderId+":"+content;
		producerService.sendTopicMessage(topic,message);
		
		//给所有订阅此主题的所有在线人发布消息，存入消息队列
		User sender=userRepository.getOne(senderId);
		Notify notify =notifyRepository.save(new Notify(content, 2, targetId, targetType, action, senderId,sender.getUserName()));
		notifyRemind(senderId,targetType,action,notify);
		return notify;
	}

	@Override
	public UserNotify createMessage(String content, Integer senderId, Integer receiverId) {
		User user=userRepository.getOne(senderId);
		Notify notify = new Notify(content, 3, null, "None", "None", senderId,user.getUserName());
		notify = notifyRepository.save(notify);
		return userNotifyRepository.save(new UserNotify(false, receiverId, notify.getNotifyId()));
	}

	@Override
	public Notify pullAnnounce(Integer userId) {
		Notify notify = notifyRepository.findNotifyByLastTime();
		UserNotify userNotify = userNotifyRepository.findAllByNotifyIdAndUserId(notify.getNotifyId(),userId);
		if (userNotify != null) {
			if (userNotify.isRead()) {

			} else {
				userNotifyRepository.save(userNotify);
			}
		} else {
			userNotifyRepository.save(new UserNotify(false, userId, notify.getNotifyId()));
		}
		return notify;
	}

	@Override
	public Notify notifyRemind(Integer targetId,String targetType,String action,Notify notify){
		List<Integer> userIds=subscriptionRepository.findUserByNotifyParam(targetId, targetType, action);
		List<User> users=userIds.stream().map(e->userRepository.getOne(e)).collect(Collectors.toList());
		userIds.stream().forEach(e->{
			userNotifyRepository.save(new UserNotify(false, e, notify.getNotifyId()));
		});
		return notify;
	}
	
	@Override
	public List<Notify> pullRemind(Integer userId) {
		List<Notify> notifies = notifyRepository.findAllByUserId(userId, 2);
/*		List<Subscription> subscriptions = subscriptionRepository.findAllByUserId(userId);
		List<Notify> notifies = new ArrayList<>();
		for (Subscription subscription : subscriptions) {
			notifies.add(notifyRepository.findOneBySubscriptionParam(subscription.getTargetId(),
					subscription.getTargetType(), subscription.getAction(), subscription.getCreatedAt()));
		}*/
	/*	notifies.stream().forEach(System.out::println);*/
/*		SubscriptionConfig subscriptionConfig=subscriptionConfigRepository.findOneByUserId(userId);
		if(subscriptionConfig==null) {
			subscriptionConfig=subscriptionConfigRepository.findOneByDefault();
		}*/
/*		HashMap<String,Boolean> config =new HashMap();
		List<Notify> result=notifies.stream().filter(e-> config.get(e.getAction())).collect(Collectors.toList());*/
		
/*		for(Notify notify:result) {
			userNotifyRepository.save(new UserNotify(false, userId, notify.getNotifyId()));
		}
		return result;*/
		//「someone do something in someone's something」
		notifies.stream().forEach(System.out::println);
		return notifies;
	}
	@Override
	public Long getUnreadRemind(Integer userId) {
		Long result = userNotifyRepository.countByUserId(userId);
		return result;
	}

	@Override
	public String subscribe(Integer userId, Integer targetId, String targetType, String reasion) {
		//根据reasion得到actions
		List<String> actions=Arrays.asList(reasion.split(":"));
		for(String action:actions) {
			subscriptionRepository.save(new Subscription(targetId,targetType,action,userId));
		}
		//订阅之后的处理：给被订阅人提醒
		if(targetType.equals("用户")) {
			User user=userRepository.getOne(userId);
			String queue="Online.User."+targetId;
			String message=user.getUserId()+":"+user.getUserName();
		    String topic="Online.User."+targetId+".subscribe";
			producerService.sendQueueMessage(queue, message);
			Notify notify = notifyRepository.save(new Notify(message, 4, targetId, "用户", "关注", userId,user.getUserName()));
			userNotifyRepository.save(new UserNotify(false, targetId, notify.getNotifyId()));
			return topic;
		}else {
			return null;
		}
	}

	@Override
	public String cancelSubscription(Integer userId, Integer targetId, String targetType) {
		subscriptionRepository.deleteByNotifyParam(targetId,targetType,userId);
		if(targetType.equals("用户")) {
			User user=userRepository.getOne(userId);
			String queue="Online.User."+targetId;
			String message=user.getUserId()+":"+user.getUserName();
		    String topic="Online.User."+targetId+".subscribe";
			producerService.sendQueueMessage(queue, message);
			Notify notify = notifyRepository.save(new Notify(message, 5, targetId, "用户", "取消关注", userId,user.getUserName()));
			userNotifyRepository.save(new UserNotify(false, targetId, notify.getNotifyId()));
			return topic;
		}else {
			return null;
		}
	}
	@Override
	public List<Subscription> getSubscription(Integer userId) {
		return subscriptionRepository.findAllByUserId(userId);
	}

/*	@Override
	public SubscriptionConfig getSubscriptionConfig(Integer userId) {
		return subscriptionConfigRepository.findOneByUserId(userId);
	}

	@Override
	public SubscriptionConfig updateSubscriptionConfig(SubscriptionConfig config) {
		return subscriptionConfigRepository.save(config);
	}*/

	@Override
	public List<UserNotify> getUserNotify(Integer userId) {
		return userNotifyRepository.findAllByUserId(userId);
	}

	@Override
	public boolean read(Integer userId, Integer... notifyIds) {
		for(Integer notifyId:notifyIds) {
			userNotifyRepository.updateReadByNotifyIdAndUserId(notifyId,userId);
		}
		return true;
	}
	@Override
	public void publish(Article article) {
		articleRepository.save(article);
		String topic="Online.User."+article.getUserId()+".subscribe";
		String message=article.getUserId()+":"+article.getTitle();
		producerService.sendTopicMessage(topic,message);
	}
}
